package com.example.bbook.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bbook.entity.*;
import com.example.bbook.mapper.*;
import com.example.bbook.services.OrderService;
import com.example.bbook.util.HashMapTool;
import com.example.bbook.util.PageTool;
import com.example.bbook.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingMapper shoppingMapper;

    @Autowired
    private SpeciesMapper speciesMapper;

    @Override
    public HashMap<String, Object> findAll(PageTool pageConfig, OrderEntity data) {
        HashMapTool hashMapTool = new HashMapTool();
        Integer page = 1, pageSize = 10;
        if (pageConfig.normal()) {
            page = pageConfig.getPage();
            pageSize = pageConfig.getPageSize();
        }
        IPage<OrderEntity> userPage = new Page<>(page, pageSize);
        QueryWrapper<OrderEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.orderByDesc("id");

        if (data.getUserId() != null) {
            userQueryWrapper.like("user_id", data.getUserId());
        }

        if (data.getGoodsId() != null) {
            userQueryWrapper.like("goods_id", data.getGoodsId());
        }

        if (data.getName() != null) {
            userQueryWrapper.like("name", data.getName());
        }

        if (data.getIsDel() != null) {
            if (data.getIsDel() == 0) {
                data.setIsDel(47);
            } else if (data.getIsDel() == 1) {
                data.setIsDel(48);
            } else if (data.getIsDel() == -1) {
                data.setIsDel(49);
            }
            userQueryWrapper.eq("is_del", data.getIsDel());
        }
        ArrayList<HashMap<String, Object>> orderTypeArr = new ArrayList<>();
        QueryWrapper<SpeciesEntity> speciesEntityQueryWrapperOrderType = new QueryWrapper<>();
        speciesEntityQueryWrapperOrderType.eq("dict_type", "order_status");

        speciesMapper.selectList(speciesEntityQueryWrapperOrderType).forEach(item -> {
            orderTypeArr.add(hashMapTool.getListKeyValue(item.getName(), item.getId(), item.getTitle()));
        });

        userPage = orderMapper.selectPage(userPage, userQueryWrapper);
        HashMap<String, Object> resMap = new HashMap<>();

        List<OrderEntity> orderEntityList = userPage.getRecords();
        orderEntityList.forEach(item -> {
            item.setGoods(goodsMapper.selectById(item.getGoodsId()));
            item.setOrderStatus(speciesMapper.selectById(item.getIsDel()));
            item.setIsDel(item.getIsDel() == 47 ? 0 : item.getIsDel() == 48 ? 1 : -1);
        });

        resMap.put("recode", orderEntityList);
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.push("isDel", orderTypeArr, "订单状态", new int[]{1, 1, 1, 1}, new String[]{"orderStatus", "title"});

        resMap.put("columns", orderEntity.thisColumns());
        resMap.put("total", orderMapper.selectCount(userQueryWrapper));
        return resMap;
    }

    @Override
    public Boolean add(OrderEntity data) {
        return false;
    }

    @Override
    public Response addOrder(OrderEntity data) {
        // 计算用户金额
        UserEntity userEntity = userMapper.selectById(data.getUserId());
        // 计算商品库存
        GoodsEntity goodsEntity = goodsMapper.selectById(data.getGoodsId());

        // 判断用于金额购买力
        int balance = userEntity.getMoney() - goodsEntity.getPrice() * data.getGoodsNum(); // 余额
        // 判断库存
        int inventory = goodsEntity.getInventory() - data.getGoodsNum(); // 库存

        if (balance < 0) {
            return Response.fail("余额不足");
        }

        if (inventory < 0) {
            return Response.fail("库存不足");
        }

        userEntity.setMoney(balance);
        userMapper.updateById(userEntity);
        goodsEntity.setInventory(inventory);
        goodsMapper.updateById(goodsEntity);
        // 删除购物车内容
        QueryWrapper<ShoppingEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", data.getUserId());
        userQueryWrapper.eq("goods_id", data.getGoodsId());
        shoppingMapper.delete(userQueryWrapper);

        // 添加订单
        data.setName(getRandomString());
        data.setPrice(goodsEntity.getPrice() * data.getGoodsNum());
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        data.setStartTime(sdf.format(d));
        data.setIsDel(47);

        if (orderMapper.insert(data) > 0) {
            return Response.successful();
        }

        return Response.fail("后台服务异常");
    }

    private static String getRandomString() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 64; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    @Override
    public Boolean deleteByIds(Integer[] ids) {
        return orderMapper.deleteBatchIds(Arrays.asList(ids)) == ids.length;
    }

    @Override
    public Boolean updateById(OrderEntity data) {
        data.setEndTime("");
        if (data.getIsDel() != null) {
            if (data.getIsDel() == 0) {
                data.setIsDel(47);
            } else if (data.getIsDel() == 1) {
                data.setIsDel(48);
            } else if (data.getIsDel() == -1) {
                data.setIsDel(49);
            }
            if (data.getIsDel() != 47) {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                data.setEndTime(sdf.format(d));
            }
        }

        return orderMapper.updateById(data) == 1;
    }
}
